<template>
  <div class="user-profile">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-state">
      <el-skeleton animated>
        <template #template>
          <div style="display: flex; align-items: flex-start; gap: 32px;">
            <el-skeleton-item variant="circle" style="width: 100px; height: 100px;" />
            <div style="flex: 1;">
              <el-skeleton-item variant="h3" style="width: 200px; margin-bottom: 16px;" />
              <el-skeleton-item variant="text" style="width: 120px; margin-bottom: 16px;" />
              <el-skeleton-item variant="text" style="width: 300px; margin-bottom: 16px;" />
              <el-skeleton-item variant="text" style="width: 250px;" />
            </div>
          </div>
        </template>
      </el-skeleton>
    </div>

    <template v-else>
      <!-- 用户基本信息 -->
      <div class="user-header">
        <div class="profile-content">
          <!-- 左侧头像 -->
          <div class="avatar-wrapper">
            <img 
              :src="userInfo.avatar || '/001.png'" 
              class="avatar" 
              alt="用户头像"
              @error="handleAvatarError"
            />
          </div>

          <!-- 右侧用户信息 -->
          <div class="user-info">
            <!-- 标题行：昵称和操作按钮 -->
            <div class="title-row">
              <h1 class="nickname">{{ userInfo.nickname || '未设置昵称' }}</h1>
              <div class="action-btns" v-if="!isCurrentUser">
                <el-button class="follow-btn" :type="isFollowing ? 'info' : 'primary'" round>
                  {{ isFollowing ? '已关注' : '关注' }}
                </el-button>
                <el-button class="more-btn" circle><el-icon><More /></el-icon></el-button>
              </div>
            </div>

            <!-- 小红书号 -->
            <div class="user-id">小红书号：{{ userInfo.id || '-' }}</div>

            <!-- 个人简介 -->
            <div class="bio">{{ userInfo.bio || '永远追逐梦想的小红薯~' }}</div>

            <!-- 个人信息（年龄和地址） -->
            <div class="user-meta">
              <span class="age" v-if="userInfo.age">{{ userInfo.age }}岁</span>
              <span class="location" v-if="userInfo.location">{{ userInfo.location }}</span>
            </div>

            <!-- 数据统计 -->
            <div class="user-stats">
              <div class="stat-item" @click="activeTab = 'notes'">
                <div class="number">{{ userInfo.noteCount || 0 }}</div>
                <div class="label">笔记</div>
              </div>
              <div class="stat-item" @click="activeTab = 'follows'">
                <div class="number">{{ userInfo.followCount || 0 }}</div>
                <div class="label">关注</div>
              </div>
              <div class="stat-item" @click="activeTab = 'fans'">
                <div class="number">{{ userInfo.fansCount || 0 }}</div>
                <div class="label">粉丝</div>
              </div>
              <div class="stat-item" @click="activeTab = 'collections'">
                <div class="number">{{ userInfo.collectionCount || 0 }}</div>
                <div class="label">收藏</div>
              </div>
              <div class="stat-item">
                <div class="number">{{ userInfo.likedCount || 0 }}</div>
                <div class="label">获赞与收藏</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 内容标签页 -->
      <div class="content-section">
        <el-tabs v-model="activeTab" class="profile-tabs">
          <el-tab-pane label="笔记" name="notes">
            <div class="notes-grid" v-if="postsLoading">
              <div v-for="i in 6" :key="i" class="skeleton-post">
                <el-skeleton animated>
                  <template #template>
                    <el-skeleton-item variant="image" style="width: 100%; height: 200px;" />
                    <div style="padding: 10px;">
                      <el-skeleton-item variant="h3" style="width: 80%; margin-bottom: 8px;" />
                      <el-skeleton-item variant="text" style="width: 60%;" />
                    </div>
                  </template>
                </el-skeleton>
              </div>
            </div>
            <div v-else-if="userPosts.length === 0" class="empty-state">
              <el-empty description="该用户暂无笔记" />
            </div>
            <div v-else class="notes-grid">
              <PostCard 
                v-for="post in userPosts" 
                :key="post.id" 
                :post="post"
                class="note-item" 
                @preview="handlePostPreview"
              />
            </div>
            
            <!-- 分页控件 -->
            <div class="pagination" v-if="userPosts.length > 0">
              <el-pagination
                :current-page="currentPage"
                :page-size="pageSize"
                :total="totalPosts"
                layout="prev, pager, next"
                @current-change="handlePageChange"
              />
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="收藏" name="collections">
            <div class="collections-grid" v-if="collectionsLoading">
              <div v-for="i in 6" :key="i" class="skeleton-post">
                <el-skeleton animated>
                  <template #template>
                    <el-skeleton-item variant="image" style="width: 100%; height: 200px;" />
                    <div style="padding: 10px;">
                      <el-skeleton-item variant="h3" style="width: 80%; margin-bottom: 8px;" />
                      <el-skeleton-item variant="text" style="width: 60%;" />
                    </div>
                  </template>
                </el-skeleton>
              </div>
            </div>
            <div v-else-if="userCollections.length === 0" class="empty-state">
              <el-empty description="该用户暂无收藏" />
            </div>
            <div v-else class="collections-grid">
              <PostCard 
                v-for="post in userCollections" 
                :key="post.id" 
                :post="post"
                class="collection-item" 
                @preview="handlePostPreview"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </template>

    <!-- 帖子预览弹窗 -->
    <PostPreview
      v-model:visible="previewVisible"
      :post-id="currentPostId"
      @refresh="fetchUserPosts"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useUserStore } from '@/store/user'
import { usePostStore } from '@/store/post'
import PostCard from '@/components/common/PostCard.vue'
import PostPreview from '@/components/common/PostPreview.vue'
import { More } from '@element-plus/icons-vue'

const route = useRoute()
const userStore = useUserStore()
const postStore = usePostStore()

const userId = ref(route.params.userId || userStore.userInfo?.id)
const userInfo = ref({})
const activeTab = ref('notes')
const loading = ref(true)
const postsLoading = ref(false)
const collectionsLoading = ref(false)

// 预览相关
const previewVisible = ref(false)
const currentPostId = ref(null)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(12)
const totalPosts = ref(0)

// 用户发布的笔记
const userPosts = ref([])
// 用户收藏的笔记
const userCollections = ref([])

// 判断是否是当前用户
const isCurrentUser = computed(() => {
  return userId.value === userStore.userInfo?.id
})

// 关注状态（需要从后端获取）
const isFollowing = ref(false)

// 头像加载错误处理
const handleAvatarError = (event) => {
  event.target.src = '/001.png'
}

// 处理帖子预览
const handlePostPreview = (postId) => {
  currentPostId.value = postId
  previewVisible.value = true
}

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  fetchUserPosts()
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    loading.value = true
    // 根据userId获取用户信息
    if (userId.value === userStore.userInfo?.id) {
      // 当前用户，从store获取
      await userStore.fetchCurrentUserInfo()
      userInfo.value = { ...userStore.userInfo }
    } else {
      // 其他用户，调用API
      // 使用API接口获取用户信息
      const response = await userStore.fetchUserInfo(userId.value)
      if (response && response.data) {
        userInfo.value = response.data
      }
    }
  } catch (error) {
    console.error('获取用户信息失败', error)
  } finally {
    loading.value = false
  }
}

// 获取用户帖子
const fetchUserPosts = async () => {
  try {
    postsLoading.value = true
    // 使用API接口获取用户帖子
    const response = await postStore.fetchUserPosts(userId.value, {
      page: currentPage.value,
      limit: pageSize.value
    })
    if (response && response.data) {
      userPosts.value = response.data.list || []
      totalPosts.value = response.data.total || 0
    }
  } catch (error) {
    console.error('获取用户帖子失败', error)
  } finally {
    postsLoading.value = false
  }
}

// 获取用户收藏
const fetchUserCollections = async () => {
  try {
    collectionsLoading.value = true
    // 使用API接口获取用户收藏
    const response = await postStore.fetchUserCollections(userId.value, {
      page: currentPage.value,
      limit: pageSize.value
    })
    if (response && response.data) {
      userCollections.value = response.data.list || []
    }
  } catch (error) {
    console.error('获取用户收藏失败', error)
  } finally {
    collectionsLoading.value = false
  }
}

// 监听标签页变化
watch(activeTab, (newTab) => {
  if (newTab === 'notes' && userPosts.value.length === 0) {
    fetchUserPosts()
  } else if (newTab === 'collections' && userCollections.value.length === 0) {
    fetchUserCollections()
  }
})

// 初始化
onMounted(async () => {
  await fetchUserInfo()
  await fetchUserPosts()
})
</script>

<style lang="scss" scoped>
.user-profile {
  padding: 24px;
  max-width: 1000px;
  margin: 0 auto;
  min-height: calc(100vh - 48px);
  background: white;
  border-radius: 12px;

  .loading-state {
    padding: 24px;
  }

  .user-header {
    margin-bottom: 40px;
    padding: 0 20px;

    .profile-content {
      display: flex;
      gap: 32px;
      margin: 0 auto;
      max-width: 800px;

      .avatar-wrapper {
        flex-shrink: 0;
        .avatar {
          width: 120px;
          height: 120px;
          border-radius: 50%;
          object-fit: cover;
          border: 1px solid #f0f0f0;
        }
      }

      .user-info {
        flex: 1;

        .title-row {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;

          .nickname {
            font-size: 26px;
            font-weight: 600;
            color: #333;
            margin: 0;
          }

          .action-btns {
            display: flex;
            gap: 12px;

            .follow-btn {
              min-width: 100px;
              height: 36px;
              font-size: 15px;
              background-color: #ff2442;
              border-color: #ff2442;

              &:hover {
                background-color: #ff4060;
                border-color: #ff4060;
              }
            }

            .more-btn {
              width: 36px;
              height: 36px;
              padding: 0;
              background: transparent;
              border: 1px solid #e4e4e4;
              color: #666;

              &:hover {
                background-color: #f7f7f7;
                border-color: #e4e4e4;
              }

              .el-icon {
                font-size: 20px;
              }
            }
          }
        }

        .user-id {
          font-size: 14px;
          color: #999;
          margin-bottom: 12px;
        }

        .bio {
          font-size: 14px;
          color: #666;
          line-height: 1.6;
          margin-bottom: 12px;
          padding-right: 40px;
        }

        .user-meta {
          display: flex;
          gap: 16px;
          color: #999;
          font-size: 14px;
          margin-bottom: 16px;
        }

        .user-stats {
          display: flex;
          gap: 48px;
          padding-top: 16px;
          border-top: 1px solid #f0f0f0;

          .stat-item {
            cursor: pointer;
            
            .number {
              font-size: 18px;
              font-weight: 600;
              color: #333;
              margin-bottom: 4px;
            }

            .label {
              font-size: 14px;
              color: #999;
            }

            &:hover {
              .number {
                color: #ff2442;
              }
            }
          }
        }
      }
    }
  }

  .content-section {
    padding: 0;

    .profile-tabs {
      :deep(.el-tabs__header) {
        margin-bottom: 24px;
      }

      :deep(.el-tabs__nav-wrap::after) {
        height: 1px;
        background-color: #f0f0f0;
      }

      :deep(.el-tabs__item) {
        font-size: 16px;
        padding: 0 24px;
        height: 48px;
        line-height: 48px;
        
        &.is-active {
          font-weight: 600;
          color: #333;
        }
      }
    }

    .notes-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
      gap: 24px;
      margin: 0 auto;
      padding: 0 24px;

      .note-item {
        background: white;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        transition: transform 0.2s ease, box-shadow 0.2s ease;

        &:hover {
          transform: translateY(-4px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
      }
    }
  }
}</style>
